﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MiniBottles.Models
{
    public class Helper
    {
        public static Bitmap ScaleImage(Image oldImage,int maxSize = 0, int widthSize = 0, int heightSize = 0)
        {
            double resizeFactor = 1;
            if (widthSize > 0)
            {
                double widthFactor = Convert.ToDouble(oldImage.Width) / widthSize;
                resizeFactor = widthFactor;
            }
            else if (heightSize > 0)
            {
                double heightFactor = Convert.ToDouble(oldImage.Height) / heightSize;
                resizeFactor = heightFactor;
            }
            else if (maxSize > 0 && (oldImage.Width > maxSize || oldImage.Height > maxSize))
            {
                double widthFactor = Convert.ToDouble(oldImage.Width) / maxSize;
                double heightFactor = Convert.ToDouble(oldImage.Height) / maxSize;
                resizeFactor = Math.Max(widthFactor, heightFactor);

            }
            int width = Convert.ToInt32(oldImage.Width / resizeFactor);
            int height = Convert.ToInt32(oldImage.Height / resizeFactor);
            Bitmap newImage = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(newImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(oldImage, 0, 0, newImage.Width, newImage.Height);
            return newImage;
        }
        public static string SaveFiles(HttpPostedFileBase file, string path)
        {
            var fileName = string.Empty;
            if (file != null)
            {
                var guid = Guid.NewGuid();
                fileName = guid + "_" + Path.GetFileName(file.FileName);

                Image img = Image.FromStream(file.InputStream, true, true);

                Image bigImg = Helper.ScaleImage(img, heightSize : 600);
                var pathbig = Path.Combine(path + "big", fileName);
                bigImg.Save(pathbig);
                


                Image img2 = Image.FromStream(file.InputStream, true, true);

                Image thumb = Helper.ScaleImage(img2, maxSize:150);
                var pathmini = Path.Combine(path + "mini", fileName);
                thumb.Save(pathmini);
            }

            return fileName;
        }

        public static bool IsPL(object info)
        {
            bool result = true;
            if (info != null)
            {
                CultureInfo cul = info as CultureInfo;
                if(cul.Name == "en-GB")
                    result = false;
            }
            return result;
        }
       
    }
}